const express = require('express');
const router = express.Router();
const pool = require('./db.js');
const { generateDataHash,decryptForUser } = require('./userDataEncryption.js');

// 获取教师课程的助教列表（使用明文）
router.get('/get-course-tutors', async (req, res) => {
    const { courseCode } = req.query;
    try {
        const [rows] = await pool.execute(`
            SELECT t.tutor_id, t.tutor_name, t.tutor_student_id, t.course_code, c.course_name
            FROM tutors t
            JOIN courses c ON t.course_code = c.course_code
            WHERE t.course_code = ?
        `, [courseCode]);
        
        // 直接返回明文数据
        res.json(rows);
    } catch (error) {
        console.error('获取课程助教失败:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 添加助教（已简化）
router.post('/add-tutor', async (req, res) => {
    const { courseCode, studentId } = req.body;
    
    try {
        // 1. 检查助教数量是否超过3个
        const [countRows] = await pool.execute(
            'SELECT COUNT(*) as count FROM tutors WHERE course_code = ?', 
            [courseCode]
        );
        if (countRows[0].count >= 3) {
            return res.status(400).json({ message: '每个课程的助教数量不能超过3个' });
        }

        // 2. 使用学号哈希查询用户
        const studentIdHash = generateDataHash(studentId);
        const [userRows] = await pool.execute(
            'SELECT user_id, name, student_id FROM users WHERE student_id_hash = ? AND role = "助教"', 
            [studentIdHash]
        );
        
        if (userRows.length === 0) {
            return res.status(404).json({ message: '助教不存在或用户不是助教' });
        }

        const user = userRows[0];
        
        // 3. 解密用户数据
        const decryptedName = decryptForUser(user.user_id, user.name);
        const decryptedStudentId = decryptForUser(user.user_id, user.student_id);

        // 4. 检查是否已经是该课程的助教
        const [existingRows] = await pool.execute(
            'SELECT * FROM tutors WHERE tutor_id = ? AND course_code = ?', 
            [user.user_id, courseCode]
        );
        
        if (existingRows.length > 0) {
            return res.status(400).json({ message: '该助教已经是本课程的助教' });
        }

        // 5. 添加助教（使用解密后的数据）
        await pool.execute(
            'INSERT INTO tutors (tutor_id, course_code, tutor_name, tutor_student_id) VALUES (?, ?, ?, ?)', 
            [user.user_id, courseCode, decryptedName, decryptedStudentId]
        );
        
        res.json({ 
            message: '助教添加成功',
            tutorName: decryptedName,
            studentId: decryptedStudentId
        });
    } catch (error) {
        console.error('添加助教失败:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 移除助教（无需修改）
router.post('/remove-tutor', async (req, res) => {
    const { tutorId } = req.body;
    try {
        const [result] = await pool.execute('DELETE FROM tutors WHERE tutor_id = ?', [tutorId]);
        if (result.affectedRows > 0) {
            res.json({ message: '助教移除成功' });
        } else {
            res.status(404).json({ message: '助教未找到' });
        }
    } catch (error) {
        console.error('移除助教失败:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 检查用户是否为助教且拥有课程权限（无需修改）
router.get('/check-tutor-permission', async (req, res) => {
    const { tutor_id, course_code } = req.query;
    try {
        // 检查用户角色是否为助教
        const [userRows] = await pool.execute('SELECT role FROM users WHERE user_id =?', [tutor_id]);
        if (userRows.length === 0 || userRows[0].role !== '助教') {
            return res.json({ hasPermission: false });
        }

        // 检查助教是否被分配到该课程
        const [tutorRows] = await pool.execute(
            'SELECT * FROM tutors WHERE tutor_id =? AND course_code =?',
            [tutor_id, course_code]
        );
        
        res.json({ hasPermission: tutorRows.length > 0 });
    } catch (error) {
        console.error('检查助教权限失败:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 获取课程助教姓名列表（使用明文）
router.get('/get-course-tutor-names', async (req, res) => {
    try {
        const { courseCode } = req.query;
        
        // 直接查询tutors表获取明文姓名
        const [tutors] = await pool.execute(
            `SELECT tutor_id, tutor_name AS name 
             FROM tutors 
             WHERE course_code = ?`, 
            [courseCode]
        );
        
        if (tutors.length === 0) {
            return res.json({ tutors: [], tutorNames: "暂无助教" });
        }
        
        // 直接生成姓名列表
        const tutorNames = tutors.map(t => t.name).join(', ');
        
        res.json({ 
            tutors,
            tutorNames: tutorNames || "暂无助教"
        });
    } catch (error) {
        console.error('获取课程助教姓名失败:', error);
        res.status(500).json({ error: '获取课程助教信息失败' });
    }
});

module.exports = router;